<?php
//封装mysql 操作类
namespace Shop;
//判断权限
if(!defined("SHOP")){
    header("Location:../index.php");
}

class Mypdo{
    //1.定义属性
    private $type;//类型
    private $host;//地址
    private $port;//端口
    private $user;//账号
    private $pass;//密码
    private $dbname;//数据库名
    private $charset;//字符集

    public $pdo;  //pdo对象

//    2.利用构造方法初始化属性
    public function __construct()
    {
        //读取配置文件
        $this->type=$GLOBALS['Config']['db_type'];
        $this->host=$GLOBALS['Config']['db_host'];
        $this->port=$GLOBALS['Config']['db_port'];
        $this->user=$GLOBALS['Config']['db_user'];
        $this->pass=$GLOBALS['Config']['db_pass'];
        $this->dbname=$GLOBALS['Config']['db_name'];
        $this->charset=$GLOBALS['Config']['db_charset'];

        $this->pdo_connect(); //连接数据库

        //设置错误类型
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE,\PDO::ERRMODE_EXCEPTION);
        //设置字段大小写
        $this->pdo->setAttribute(\PDO::ATTR_CASE,\PDO::CASE_LOWER);
    }

    //3.连接数据库
    private function pdo_connect(){
        try{

            //在有命名空间的类文件里面实例化系统类需要加上命名空间
           $this->pdo=new \PDO("{$this->type}:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}","{$this->user}","{$this->pass}");

        }catch (\PDOException $e){
            echo "错误! <br/>";
            echo "错误文件!:".$e->getFile()." <br/>";
            echo "错误编码!:".$e->getCode()." <br/>";
            echo "错误信息!:".$e->getMessage()." <br/>";
        }
    }

    //执行方法
    public function pdo_query_i($sql){
       $this->pdo->exec($sql);
        return $this->pdo->lastInsertID();
    }

    //5.查询操作
    public function pdo_sel($sql,$type=1){
        $res=$this->pdo->query($sql);

        //返回类型
        $res->setFetchMode(\PDO::FETCH_ASSOC); //设置fetch 的模式为获取关联数组

        if($type==1){
            return $res->fetch();
        }else{
            return $res->fetchAll();
        }
    }

    //6.插入方法
    //$arr : 数据 字段对应下标
    //$table : 操作的表
    public function pdo_ins($arr,$table){
        $sql="insert into $table set ";
        foreach ($arr as $k=>$v){
            $sql.="`$k`='$v',";
        }
        $sql=trim($sql,',');

        $this->pdo->exec($sql);

        return $this->pdo->lastInsertID();
    }

    //7.修改方法
    public function pdo_upd($arr,$table,$where){
        $sql="update $table set ";
        foreach ($arr as $k=>$v){
            $sql.="`$k`='$v',";
        }
        $sql=trim($sql,',');

        $sql.=" where ".$where;

       return $this->pdo->exec($sql);
    }

    //8.删除方法
//    $table : 表名
//    $where : 条件
    public function pdo_del($table,$where){
        $sql="delete from $table where $where";
        return $this->pdo->exec($sql);
    }

}

